import { ref } from 'vue';
import api from '../api/api';

// 图片上传组合函数
export const useImageUpload = () => {
  const loading = ref(false);
  const error = ref('');

  // 处理图片上传
  const uploadImage = async (file) => {
    if (!file) {
      console.error('上传失败：file 为 undefined');
      return null;
    }

    loading.value = true;
    error.value = '';

    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await api.post('/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      if (response.data.code === 1 && response.data.msg === 'success') {
        return response.data.data; // 返回图片URL
      } else {
        throw new Error('图片上传失败');
      }
    } catch (err) {
      console.error('图片上传出错:', err);
      error.value = '图片上传失败，请重试';
      return null;
    } finally {
      loading.value = false;
    }
  };

  // 新增：处理图片插入逻辑
  const handleImageAdded = async (file, Editor, cursorLocation) => {
    const imageUrl = await uploadImage(file);
    if (imageUrl) {
      Editor.insertEmbed(cursorLocation, 'image', imageUrl);
    } else {
      alert(error.value || '图片插入失败');
    }
  };

  return { uploadImage, handleImageAdded, loading, error };
};